package com.md.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;



public class ImageBinary {
	
	public static String getImageBase64(String imgFilePath) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }

	public static String getImageBase64(InputStream in) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }
	
	/**
	 * @Description: 将base64编码字符串转换为图片
	 * @Author: 
	 * @CreateTime: 
	 * @param imgStr base64编码字符串
	 * @param path 图片路径-具体到文件
	 * @return
	*/
	public static byte[] generateImage(String imgStr) {
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte []  imageBytes = decoder.decodeBuffer(imgStr);
			if(imageBytes!=null){
				return imageBytes;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static void main(String[] args) {
		File directory = new File("");
		String imgStr ="";
		try {
			String courseFile = directory.getCanonicalPath()+"/logo.jpg" ;
			courseFile ="D:/logo.jpg";
			imgStr = getImageBase64(courseFile); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(imgStr);
		OutputStream out;
		try {
			out = new FileOutputStream("D:/test.jpg");
			out.write(generateImage(imgStr));
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}
